<?php


namespace app\api\controller;

use adjust\SendS2sAdjust;
use app\api\model\CustomerServiceAccount;
use app\api\model\CustomerServiceAccountMiddle;
use app\api\model\CustomerServiceGroup;
use app\api\model\CustomerServicePersonnel;
use app\api\model\Partner;
use app\api\model\User;
use app\common\controller\api\Base;
use think\Cache;
use think\Log;

/**
 * 分配到用户策略  方针 用户进来后 分配给第一个合作方下的第一个客服组下的 第一个客服  依次是 第二个合作方下的第一个客服组 下的第一个客服 以此类推
 * Class Distributionuser
 */
class Distributionuser
{
    //模拟上报
    public function test()
    {
        $userInfo = User::get(7150);
        $sendS2sAdjust = new SendS2sAdjust();
        $sendS2sAdjust->sendAdjust($userInfo['id'], 'reg', $userInfo['app_base_id'], [], ['phone' => $userInfo['username'], 'source' => $userInfo['channel']]);
        echo 123;
        die();
    }

    //超量分配逻辑
    public function DistributionUserExcess($appBaseId = 11)
    {
        //获取今日分配总数
        $time = time();
        $startOpenTime = strtotime(date('Y-m-d', $time) . '00:00:00');//格式化开始时间
        $endOpenTime = strtotime(date('Y-m-d', $time) . '23:59:59');//格式化结束时间


        //获取所有客服今日分配总数
        //获取所有开启的合作方
        $partnerIds = Partner::field('id')
            ->where([
                'status' => 1,
                'is_del' => 0
            ])
            ->select()
            ->toArray();
        $partnerIds = array_column($partnerIds, 'id');
        //获取所有开启的客服组
        $groupIds = CustomerServiceGroup::field('id')
            ->where([
                'switch' => 1,
                'partner_id' => ['in', $partnerIds],
                'is_del' => 0,
            ])
            ->select()
            ->toArray();
        $groupIds = array_column($groupIds, 'id');
        //获取可分配客服数
        $distributionPartnerNumTotal = CustomerServicePersonnel::field('id')
            ->where([
                'switch' => 1,
                'customer_service_group_id' => ['in', $groupIds],
                'is_del' => 0,
            ])
            ->sum('distribution_user_num');
        //获取今日所有开启的客服
        $PersonnelList = CustomerServicePersonnel::field('id')
            ->where([
                'switch' => 1,
                'customer_service_group_id' => ['in', $groupIds],
                'is_del' => 0,
            ])
            ->select()
            ->toArray();
        $PersonnelIds = array_column($PersonnelList, 'id');
        //查找当前开启的客服的客服账号
        //查找当前客服是否有开启的客服账号
        $accountWhere = [
            'is_del' => 0,
            'status' => 1,
            'switch' => 1,
            'customer_service_personnel_id' => ['in', $PersonnelIds],
//            'app_base_id' => $appBaseId,
        ];
        $accountList = CustomerServiceAccount::field('id')->where($accountWhere)->select()->toArray();
        $accountIds = array_column($accountList, 'id');
        //获取账号中间表数据
        $accountMiddleList = CustomerServiceAccountMiddle::field('id')->where([
            'customer_service_account_id' => ['in', $accountIds]
        ])->select()->toArray();
        $accountMiddleIds = array_column($accountMiddleList, 'id');
        //获取今日所有开启的客服的分配总量
        $distributionPartnerUser = [
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_account_middle_id' => ['in', $accountMiddleIds]
        ];
        $distributionPartnerUserNumTotal = User::where($distributionPartnerUser)->count('id');

        if ($distributionPartnerUserNumTotal >= $distributionPartnerNumTotal) {
            $ExcessPersonnelIdKey = 'ExcessPersonnelIdKey:' . $appBaseId;
            //获取上一次超量分配的客服id
            $personnelId = Cache::store('redis')->get($ExcessPersonnelIdKey);
            if (empty($personnelId)) {
                //获取所有未关闭的的客服人员
                $personnelWhere = [
                    'switch' => 1,
                    'is_del' => 0,
                    'is_excess_switch' => 1
                ];
                //当一轮客服都分配完成后 从第一个客服继续开始
                $personnelInfo = CustomerServicePersonnel::field('id,partner_id,customer_service_group_id')->where($personnelWhere)->order('id', 'asc')->find();
                //整个系统都没有打开的客服抛出
                if (empty($personnelInfo)) {
                    return false;
                }
                $personnelId = $personnelInfo['id'];
                Cache::store('redis')->set($ExcessPersonnelIdKey, $personnelInfo['id']);
            } else {
                $personnelWhere = [
                    'switch' => 1,
                    'is_del' => 0,
                    'is_excess_switch' => 1,
                    'id' => ['>', $personnelId]
                ];
                $personnelInfo = CustomerServicePersonnel::field('id,distribution_user_num,partner_id,customer_service_group_id')->where($personnelWhere)->order('id', 'asc')->find();
                if (empty($personnelInfo)) {
                    Cache::store('redis')->rm($ExcessPersonnelIdKey);
                    return $this->DistributionUserExcess($appBaseId);
                }
                $personnelId = $personnelInfo['id'];
                Cache::store('redis')->set($ExcessPersonnelIdKey, $personnelInfo['id']);
            }
            //查找当前客服是否有开启的客服账号
            $accountWhere = [
                'is_del' => 0,
                'status' => 1,
                'switch' => 1,
                'customer_service_personnel_id' => $personnelId,
                'app_base_id' => $appBaseId,
            ];
            $accountInfo = CustomerServiceAccount::where($accountWhere)->find();
            //客服下未添加账号 则直接分配给下一个客服
            if (empty($accountInfo)) {
                //返回客服账号
                return $this->DistributionUserExcess($appBaseId);
            }
            //获取账号中间表数据
            $accountMiddleInfo = CustomerServiceAccountMiddle::get(['customer_service_account_id' => $accountInfo['id']]);
            return $accountMiddleInfo['id'];
        }
        return false;
    }

    //重写分配逻辑
    public function DistributionUserPartner($appBaseId = 11)
    {
        //新流程app  用户注册直接分配给虚拟客服
        if ($appBaseId == 18) {
            return 1158;
        }
        //TODO 超量分配逻辑(已测试完成 暂时关闭 有需要的时候打开)
        $distributionId = $this->DistributionUserExcess($appBaseId);
        if ($distributionId) {
//           echo 123;
            return $distributionId;
        }
        //获取今日分配总数
        $time = time();
        $startOpenTime = strtotime(date('Y-m-d', $time) . '00:00:00');//格式化开始时间
        $endOpenTime = strtotime(date('Y-m-d', $time) . '23:59:59');//格式化结束时间

        $personnelIdKey = 'personnelIdKey:' . $appBaseId;
        //获取上一次分配的客服id
        $personnelId = Cache::store('redis')->get($personnelIdKey);
        if (empty($personnelId)) {
            //获取所有未关闭的的客服人员
            $personnelWhere = [
                'switch' => 1,
                'is_del' => 0,
                'distribution_user_num' => ['>', 0]
            ];
            //当一轮客服都分配完成后 从第一个客服继续开始
            $personnelInfo = CustomerServicePersonnel::field('id,partner_id,customer_service_group_id,distribution_user_num')->where($personnelWhere)->order('id', 'asc')->find();

            //整个系统都没有打开的客服抛出
            if (empty($personnelInfo)) {
                return false;
            }
//            $personnelId = $personnelInfo['id'];
            Cache::store('redis')->set($personnelIdKey, $personnelInfo['id']);
        } else {
            $personnelWhere = [
                'switch' => 1,
                'is_del' => 0,
                'distribution_user_num' => ['>', 0],
                'id' => ['>', $personnelId]
            ];
            $personnelInfo = CustomerServicePersonnel::field('id,distribution_user_num,partner_id,customer_service_group_id')->where($personnelWhere)->order('id', 'asc')->find();
            if (empty($personnelInfo)) {
                Cache::store('redis')->rm($personnelIdKey);
                return $this->DistributionUserPartner($appBaseId);
            }
//            $personnelId = $personnelInfo['id'];
            Cache::store('redis')->set($personnelIdKey, $personnelInfo['id']);
        }

//        echo '客服id:' . $personnelInfo['id'] . "\n";

        //判断当前合作方是否分配满员
        //获取合作方详情
        $partnerInfo = Partner::get($personnelInfo['partner_id']);
//        //判断合作方是否拥有该app的分配权限
//        $appIds = explode(',', $partnerInfo['app_id']);
//        //没有分配权限则直接进入下一个
//        if (!array_search($appBaseId, $appIds)) {
//            return $this->DistributionUserPartner($appBaseId);
//        }
        $accountModel = new CustomerServiceAccount();
        $partnerAccountList = $accountModel->with(['CustomerServiceAccountMiddle'])->where([
            'partner_id' => $partnerInfo['id'],
//            'app_base_id' => $appBaseId,
            'status' => 1,
            'switch' => 1,
            'is_del' => 0,
        ])
            ->select();
        if (empty($partnerAccountList)) {

            return $this->DistributionUserPartner($appBaseId);
        }
        $distributionPartnerUser = [
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_account_middle_id' => ['in', array_column($partnerAccountList->toArray(), 'customer_service_account_middle_id')]
        ];
        $distributionPartnerUserNum = User::where($distributionPartnerUser)->count('id');

//        echo '客服id:' . $personnelId . '合作方可分配数:' . $personnelInfo['distribution_user_num'] . "\n";
        if ($distributionPartnerUserNum >= $partnerInfo['distribution_user_num']) {
            return $this->DistributionUserPartner($appBaseId);
        }
        //获取客服组详情
        $groupInfo = CustomerServiceGroup::where([
            'id' => $personnelInfo['customer_service_group_id'],
            'switch' => 1
        ])->find();

        //如果客服组关闭  则直接分配给下个客服
        if (empty($groupInfo)) {

            return $this->DistributionUserPartner($appBaseId);
        }
        $groupAccountList = $accountModel->with(['CustomerServiceAccountMiddle'])
            ->where([
                'customer_service_group_id' => $groupInfo['id'],
                'status' => 1,
                'switch' => 1,
                'is_del' => 0,
//                'app_base_id' => $appBaseId,
            ])
            ->select();
        if (empty($groupAccountList)) {
            return $this->DistributionUserPartner($appBaseId);
        }
        $distributionGroupUser = [
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_account_middle_id' => ['in', array_column($groupAccountList->toArray(), 'customer_service_account_middle_id')]
        ];
        $distributionGroupUserNum = User::where($distributionGroupUser)->count('id');
//        echo '客服id:' . $personnelId . '客服组可分配数:' . $groupInfo['distribution_user_num'] . "\n";
        if ($distributionGroupUserNum >= $groupInfo['distribution_user_num']) {
            return $this->DistributionUserPartner($appBaseId);
        }
        //TODO 多账号逻辑
        $accountWhere = [
            'is_del' => 0,
            'status' => 1,
            'switch' => 1,
            'customer_service_personnel_id' => $personnelInfo['id'],
            'app_base_id' => $appBaseId,
        ];
        //获取当前分配到第几个账号
        $accountNum = CustomerServiceAccount::where($accountWhere)->count('id');
        if (empty($accountNum)) {
            //返回客服账号
            return $this->DistributionUserPartner($appBaseId);
        }

        $accountIdKey = 'accountIdKey:' . $personnelInfo['id'];
        $accountOldDigit = Cache::store('redis')->get($accountIdKey);
        if (empty($accountOldDigit)) {
            $accountOldDigit = 0;
        }
//        Cache::store('redis')->set($personnelIdKey, $personnelInfo['id']);
//        $personnelId = Cache::store('redis')->get($personnelIdKey);
        //查找当前客服是否有开启的客服账号
        $accountArr = CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])->where($accountWhere)->order('id', 'desc')->select()->toArray();
        if (empty($accountArr[$accountOldDigit])) {
            $accountOldDigit = 0;
        }
        $accountInfo = $accountArr[$accountOldDigit];
//        echo '客服id:' . $personnelId . '当前开启的客服账号:' . $accountInfo['id'] . "\n";
//        //客服下未添加账号 则直接分配给下一个客服
//        if (empty($accountInfo)) {
//            //返回客服账号
//            return $this->DistributionUserPartner($appBaseId);
//        }

        //获取账号中间表数据
        $accountMiddleInfo = CustomerServiceAccountMiddle::get(['customer_service_account_id' => $accountInfo['id']]);
//        echo '客服id:' . $personnelId . '当前开启的客服中间表id:' . $accountMiddleInfo['id'] . "\n";
        //中间表出现错误  记录日志  分配给下一个客服
        if (empty($accountMiddleInfo)) {
            Log::error('客服账号存在,中间表数据不存在:' . json_encode($accountInfo));
            return $this->DistributionUserPartner($appBaseId);
        }
        //判断当前客服是否已经分配满员
        $distributionAccountUser = [
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_account_middle_id' => ['in', array_column($accountArr, 'customer_service_account_middle_id')]
        ];
        $distributionAccountUserNum = User::where($distributionAccountUser)->count();
//        echo '客服id:' . $personnelId . '客服人员可分配数:' . $personnelInfo['distribution_user_num'] . "\n";
        if ($distributionAccountUserNum >= $personnelInfo['distribution_user_num']) {
            return $this->DistributionUserPartner($appBaseId);
        }
        $accountNum = $accountNum - 1;
        if ($accountOldDigit == $accountNum) {
            $accountOldDigit = 0;
        } else {
            $accountOldDigit = $accountOldDigit + 1;
        }
        Cache::store('redis')->set($accountIdKey, $accountOldDigit);
        return $accountMiddleInfo['id'];
    }

    /**
     * 新流程分配逻辑
     * 思路 : 用户注册进来  默认分配给 固定的虚拟客服  客户支付手续费后  再进行二次分配  按顺序分配给客服   同时修改用户信息
     * 注意 : 此分配逻辑 与用户是否达到分配上限无关 此分配逻辑只适用于 app_base_id为18的app
     */
    public function newDistributionUser($user_id)
    {
        //定义初始变量
        $userInfo = User::get($user_id);
        $appBaseId = 18;
        $partnerId = 11;
        if (empty($userInfo)) {
            return false;
        }
        if ($userInfo['app_base_id'] !== $appBaseId) {
            return false;
        }
        $personnelIdKey = 'NewPersonnelIdKey:' . $appBaseId;
        //获取上一次分配的客服id
        $personnelId = Cache::store('redis')->get($personnelIdKey);
//        var_dump($personnelId);
        if (empty($personnelId)) {
            //获取所有未关闭的的客服人员
            $personnelWhere = [
                'switch' => 1,
                'is_del' => 0,
                'distribution_user_num' => ['>', 0],
                'partner_id' => $partnerId
            ];
            //当一轮客服都分配完成后 从第一个客服继续开始
            $personnelInfo = CustomerServicePersonnel::field('id,partner_id,customer_service_group_id,distribution_user_num')->where($personnelWhere)->order('id', 'asc')->find();

            //整个系统都没有打开的客服抛出
            if (empty($personnelInfo)) {
                return false;
            }
            Cache::store('redis')->set($personnelIdKey, $personnelInfo['id']);
        } else {
            $personnelWhere = [
                'switch' => 1,
                'is_del' => 0,
                'distribution_user_num' => ['>', 0],
                'id' => ['>', $personnelId],
                'partner_id' => $partnerId
            ];
            $personnelInfo = CustomerServicePersonnel::field('id,distribution_user_num,partner_id,customer_service_group_id')->where($personnelWhere)->order('id', 'asc')->find();
            if (empty($personnelInfo)) {
                Cache::store('redis')->rm($personnelIdKey);
                return $this->newDistributionUser($user_id);
            }
//            $personnelId = $personnelInfo['id'];
            Cache::store('redis')->set($personnelIdKey, $personnelInfo['id']);
        }
        //获取客服组详情
        $groupInfo = CustomerServiceGroup::where([
            'id' => $personnelInfo['customer_service_group_id'],
            'switch' => 1
        ])->find();

        //如果客服组关闭  则直接分配给下个客服
        if (empty($groupInfo)) {

            return $this->newDistributionUser($user_id);
        }
        $accountWhere = [
            'is_del' => 0,
            'status' => 1,
            'switch' => 1,
            'customer_service_personnel_id' => $personnelInfo['id'],
            'app_base_id' => $appBaseId,
        ];
        //获取当前分配到第几个账号
        $accountNum = CustomerServiceAccount::where($accountWhere)->count('id');
        if (empty($accountNum)) {
            //返回客服账号
            return $this->newDistributionUser($user_id);
        }

        $accountIdKey = 'NewAccountIdKey:' . $personnelInfo['id'];
        $accountOldDigit = Cache::store('redis')->get($accountIdKey);
        if (empty($accountOldDigit)) {
            $accountOldDigit = 0;
        }
//        Cache::store('redis')->set($personnelIdKey, $personnelInfo['id']);
//        $personnelId = Cache::store('redis')->get($personnelIdKey);
        //查找当前客服是否有开启的客服账号
        $accountArr = CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])->where($accountWhere)->order('id', 'desc')->select()->toArray();
        if (empty($accountArr[$accountOldDigit])) {
            $accountOldDigit = 0;
        }
        $accountInfo = $accountArr[$accountOldDigit];
//        echo '客服id:' . $personnelId . '当前开启的客服账号:' . $accountInfo['id'] . "\n";
//        //客服下未添加账号 则直接分配给下一个客服
//        if (empty($accountInfo)) {
//            //返回客服账号
//            return $this->DistributionUserPartner($appBaseId);
//        }

        //获取账号中间表数据
        $accountMiddleInfo = CustomerServiceAccountMiddle::get(['customer_service_account_id' => $accountInfo['id']]);
//        echo '客服id:' . $personnelId . '当前开启的客服中间表id:' . $accountMiddleInfo['id'] . "\n";
        //中间表出现错误  记录日志  分配给下一个客服
        if (empty($accountMiddleInfo)) {
            Log::error('客服账号存在,中间表数据不存在:' . json_encode($accountInfo));
            return $this->newDistributionUser($user_id);
        }

        $accountNum = $accountNum - 1;
        if ($accountOldDigit == $accountNum) {
            $accountOldDigit = 0;
        } else {
            $accountOldDigit = $accountOldDigit + 1;
        }
        Cache::store('redis')->set($accountIdKey, $accountOldDigit);
//        return $accountMiddleInfo['id'];
        $userInfo->customer_service_account_middle_id = $accountMiddleInfo['id'];
        $userInfo->save();
        //清除用户客服缓存 防止创建订单的时候  出现错误
        $cacheKey = 'GET_USER_PARTNER_FIELD_KEY : ' . $userInfo['id'];
        Cache::store('redis')->rm($cacheKey);
        return true;
    }


    private static $partnerIsDistributionUserKey = 'partnerIsDistributionUserKey:';

    private static $partnerToDistributionUserNumKey = 'partnerToDistributionUserNumKey:';

    private static $groupIsDistributionUserKey = 'groupIsDistributionUserKey:';

    private static $groupToDistributionUserNumKey = 'groupToDistributionUserNumKey:';

    private static $groupCurrentDistributionUserNumKey = 'groupCurrentDistributionUserNumKey:';

    private static $personnelIsDistributionUserKey = 'personnelIsDistributionUserKey:';

    private static $personnelToDistributionUserNumKey = 'personnelToDistributionUserNumKey:';

    private static $personnelDistributionUserNumKey = 'personnelDistributionUserNumKey:';

    private static $partnerDistributionUserNumKey = 'partnerDistributionUserNumKey:';


    /**
     * 计算分配到合作方
     */
    public function DistributionUserPartnerOLD($appBaseId = 6)
    {

        //获取所有未关闭的的合作方
        $partnerWhere = [
            'status' => 1,
            'is_del' => 0,
            'app_id' => ['like', '%' . $appBaseId . '%'],
            'distribution_user_num' => ['>', 0]
        ];
        $partnerList = Partner::field('id,distribution_user_num')->where($partnerWhere)->select()->toArray();

        $partnerDistributionUserNum = Cache::store('redis')->get(self::$partnerDistributionUserNumKey);
        $partnerDistributionUserNum = empty($partnerDistributionUserNum) ? 0 : $partnerDistributionUserNum;
        if ($partnerDistributionUserNum == count($partnerList)) {
            Cache::store('redis')->rm(self::$partnerDistributionUserNumKey);
            foreach ($partnerList as $value) {
                $partnerIsDistributionUserKey = self::$partnerIsDistributionUserKey . $value['id'];
                Cache::store('redis')->rm($partnerIsDistributionUserKey);
            }
        }
        //获取所有合作方下的客服总人员  如果所有人员都分配过一次后,全部数据清空 从头开始
        $personneList = CustomerServicePersonnel::field('id')
            ->where([
                'partner_id' => ['in', array_column($partnerList, 'id')],
                'switch' => 1,
                'is_del' => 0,
                'distribution_user_num' => ['>', 0]
            ])
            ->select()
            ->toArray();
        $personnelNum = CustomerServiceAccount::where([
            'partner_id' => ['in', array_column($partnerList, 'id')],
            'customer_service_personnel_id' => ['in', array_column($personneList, 'id')],
            'status' => 1,
            'switch' => 1,
            'is_del' => 0
        ])->count('id');

        $personnelDistributionUserNum = Cache::store('redis')->get(self::$personnelDistributionUserNumKey);
        if ($personnelNum <= $personnelDistributionUserNum) {
            //说明当前一次大循环完成,清空数据从头开始
            foreach ($partnerList as $key => $value) {
                $this->DistributionUserGroup($value['id'], 1);
            }
        }
        //分配逻辑处理
        foreach ($partnerList as $key => $value) {
            //校验当前合作方是否已经分配
            $partnerIsDistributionUserKey = self::$partnerIsDistributionUserKey . $value['id'];
            $partnerIsDistributionUser = Cache::store('redis')->get($partnerIsDistributionUserKey);
            //不是空代表已分配直接跳出本次循环执行下个合作方循环
            if (!empty($partnerIsDistributionUser)) {
                continue;
            }
            //查看当前已分配数量是否到达当前合作方上限
            $partnerToDistributionUserNumKey = self::$partnerToDistributionUserNumKey . $value['id'];
            $distributionUserNum = Cache::store('redis')->get($partnerToDistributionUserNumKey);
            if (empty($distributionUserNum)) {
                $distributionUserNum = 0;
            }
            //当前合作方分配满后 跳出本次循环 执行下次逻辑
            if ($value['distribution_user_num'] <= $distributionUserNum) {
                continue;
            }
            //当合作方既没有到达上限 又没有分配时 进行下一个逻辑
            $accountMiddleId = $this->DistributionUserGroup($value['id']);
            if (empty($accountMiddleId)) {
                continue;
            }
            //缓存处理 每天12点数据清零
            $time = strtotime(date('Y-m-d') . '23:59:59') - time();
            $partnerDistributionUserNum = Cache::store('redis')->get(self::$partnerDistributionUserNumKey);
            $partnerDistributionUserNum = empty($partnerDistributionUserNum) ? 0 : $partnerDistributionUserNum;
            Cache::store('redis')->set(self::$partnerDistributionUserNumKey, $partnerDistributionUserNum + 1, $time);
            Cache::store('redis')->set($partnerIsDistributionUserKey, 1, $time);
            Cache::store('redis')->set($partnerToDistributionUserNumKey, $distributionUserNum + 1, $time);
            //终止本次循环
            break;
        }
        //TODO 之后设置策略 多余的分配给指定用户
        return empty($accountMiddleId) ? 57 : $accountMiddleId;
    }

    /**
     * 计算分配到客服组
     * @param $partnerId
     * @param $isRmCache //是否清除所有缓存
     */
    public function DistributionUserGroup($partnerId, $isRmCache = 0)
    {
        //获取所有未关闭的的客服组
        $groupWhere = [
            'switch' => 1,
            'is_del' => 0,
            'partner_id' => $partnerId,
            'distribution_user_num' => ['>', 0]
        ];
        $accountMiddleId = false;
        $groupList = CustomerServiceGroup::field('id,distribution_user_num')->where($groupWhere)->select()->toArray();
        if ($isRmCache == 1) {
            foreach ($groupList as $key => $value) {
                $this->DistributionUserPersonnel($value['id'], 1);
                $groupIsDistributionUserKey = self::$groupIsDistributionUserKey . $value['id'];
                Cache::store('redis')->rm($groupIsDistributionUserKey);
                $groupCurrentDistributionUserNumKey = self::$groupCurrentDistributionUserNumKey . $value['id'];
                Cache::store('redis')->rm($groupCurrentDistributionUserNumKey);
            }
            return true;
        }
        foreach ($groupList as $key => $value) {

            //查看当前已分配数量是否到达当前客服组上限
            $groupToDistributionUserNumKey = self::$groupToDistributionUserNumKey . $value['id'];
            $distributionUserNum = Cache::store('redis')->get($groupToDistributionUserNumKey);
            if (empty($distributionUserNum)) {
                $distributionUserNum = 0;
            }
            //判断当前客服组下是否有账号 无账号则跳过
            $accountCountWhere = [
                'customer_service_group_id' => $value['id'],
                'status' => 1,
                'is_del' => 0
            ];
            $accountCount = CustomerServiceAccount::where($accountCountWhere)->count('id');
            if (empty($accountCount)) {
                continue;
            }
            $groupCurrentDistributionUserNumKey = self::$groupCurrentDistributionUserNumKey . $value['id'];
            $groupCurrentDistributionUserNum = Cache::store('redis')->get($groupCurrentDistributionUserNumKey);
            if (empty($groupCurrentDistributionUserNum)) {
                $groupCurrentDistributionUserNum = 0;
            }
            //校验当前客服组是否已经分配
            $groupIsDistributionUserKey = self::$groupIsDistributionUserKey . $value['id'];
            $groupIsDistributionUser = Cache::store('redis')->get($groupIsDistributionUserKey);
            //不是空代表已分配 判断当前客服组分配是否满员 满员直接跳出本次循环执行下个客服组方循环
            if (!empty($groupIsDistributionUser)) {
                if ($groupCurrentDistributionUserNum >= $accountCount) {
                    continue;
                }
            }
            //当前客服组分配满后 跳出本次循环 执行下次逻辑
            if ($value['distribution_user_num'] <= $distributionUserNum) {
                continue;
            }
            $accountMiddleId = $this->DistributionUserPersonnel($value['id']);
            if (empty($accountMiddleId)) {
                continue;
            }

            //缓存处理 每天12点数据清零
            $time = strtotime(date('Y-m-d') . '23:59:59') - time();
            Cache::store('redis')->set($groupIsDistributionUserKey, 1, $time);
            Cache::store('redis')->set($groupToDistributionUserNumKey, $distributionUserNum + 1, $time);
            Cache::store('redis')->set($groupCurrentDistributionUserNum, $groupCurrentDistributionUserNum + 1, $time);
            //终止本次循环
            break;
        }
        return $accountMiddleId;
    }

    /**
     * 计算分配到客服人员
     * @param $groupId
     * @param $isRmCache //是否清除所有缓存
     */
    public function DistributionUserPersonnel($groupId, $isRmCache = 0)
    {
        //获取所有未关闭的的客服人员
        $personnelWhere = [
            'switch' => 1,
            'is_del' => 0,
            'customer_service_group_id' => $groupId,
            'distribution_user_num' => ['>', 0]
        ];
        $personnelList = CustomerServicePersonnel::field('id,distribution_user_num')->where($personnelWhere)->select()->toArray();
        if ($isRmCache == 1) {
            foreach ($personnelList as $key => $value) {
                $personnelIsDistributionUserKey = self::$personnelIsDistributionUserKey . $value['id'];
                Cache::store('redis')->rm($personnelIsDistributionUserKey);

            }
            $personnelDistributionUserNumKey = self::$personnelDistributionUserNumKey;
            Cache::store('redis')->rm($personnelDistributionUserNumKey);
            return true;
        }
        $accountMiddleId = false;
        foreach ($personnelList as $key => $value) {
            //校验当前人员是否已经分配
            $personnelIsDistributionUserKey = self::$personnelIsDistributionUserKey . $value['id'];
            $personnelIsDistributionUser = Cache::store('redis')->get($personnelIsDistributionUserKey);

            //不是空代表已分配直接跳出本次循环执行下个合作方循环
            if (!empty($personnelIsDistributionUser)) {
                continue;
            }
            //查看当前已分配数量是否到达当前人员上限
            $personnelToDistributionUserNumKey = self::$personnelToDistributionUserNumKey . $value['id'];
            $distributionUserNum = Cache::store('redis')->get($personnelToDistributionUserNumKey);
            if (empty($distributionUserNum)) {
                $distributionUserNum = 0;
            }
            //当前人员分配满后 跳出本次循环 执行下次逻辑
            if ($value['distribution_user_num'] <= $distributionUserNum) {
                continue;
            }
            //未分配满说明要分配给这个客服人员
            //查询这个人员的账号信息
            $accountWhere = [
                'is_del' => 0,
                'status' => 1,
                'switch' => 1,
                'customer_service_personnel_id' => $value['id']
            ];
            $accountInfo = CustomerServiceAccount::field('id')->where($accountWhere)->find();
            //客服账号数据出现错误  则直接分配给下一个客服
            if (empty($accountInfo)) {
                continue;
            }
            $time = strtotime(date('Y-m-d') . '23:59:59') - time();
            $personnelDistributionUserNumKey = self::$personnelDistributionUserNumKey;
            $personnelDistributionUserNum = Cache::store('redis')->get($personnelDistributionUserNumKey);
            $personnelDistributionUserNum = empty($personnelDistributionUserNum) ? 0 : $personnelDistributionUserNum;
            Cache::store('redis')->set($personnelDistributionUserNumKey, $personnelDistributionUserNum + 1, $time);
            //获取账号中间表数据

            $accountMiddleInfo = CustomerServiceAccountMiddle::get(['customer_service_account_id' => $accountInfo['id']]);
            if (empty($accountMiddleInfo)) {
                continue;
            }
            $accountMiddleId = $accountMiddleInfo['id'];
            //缓存处理 每天12点数据清零
            Cache::store('redis')->set($personnelIsDistributionUserKey, 1, $time);
            Cache::store('redis')->set($personnelToDistributionUserNumKey, $distributionUserNum + 1, $time);
            //终止本次循环
            break;
        }
        return $accountMiddleId;
    }
}